package com.cn.order.service;

import com.cn.order.entity.Order;
import com.cn.order.fegin.AccountClient;
import com.cn.order.fegin.EasyIdClient;
import com.cn.order.fegin.StorageClient;
import com.cn.order.mapper.OrderMapper;
import com.cn.order.tcc.OrderTCCAction;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private EasyIdClient easyIdClient;
    @Autowired
    private AccountClient accountClient;
    @Autowired
    private StorageClient storageClient;
    @Autowired
    private OrderTCCAction orderTCCAction;

    //    开启全局事务配置
    @GlobalTransactional
//    本地配置
    @Transactional
    @Override
    public void create(Order order) {
//        TODO:调用全局唯一一个发号器，获取一个唯一不重复的id
//        这是暂时的代码
//        long orderId=Long.valueOf(new Random().nextInt(Integer.MAX_VALUE));
//        long orderId=Math.abs(new Random().nextLong());
        /*TODO:1.远程调用库存减少库存
         *  2.远程调用账户，减少金额*/
        Long s = easyIdClient.nextId("order_business");
        order.setId(s);
//        order.setStatus(1);
// mybatis-plus 的扩展方法
//        orderMapper.insert(order);
//        orderMapper.create(order);
//        null值 ordertccaction 是一个动态代理对象，有aop添加了拦截器，
        orderTCCAction.prepare(null, order.getId(), order.getUserId(), order.getProductId(), order.getCount(), order.getMoney(), order.getStatus());
       storageClient.decrease(order.getProductId(), order.getCount());
       accountClient.decreaseAccount(order.getUserId(),order.getMoney());
//        accountClient.decreaseAccount(order.getUserId(), order.getMoney());
    }
}
